﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using CprExam.Model;
using GalaSoft.MvvmLight.Command;
using GLCommon;

namespace CprExam.ViewModel
{
    public class ExamineeLoginViewModel : VmBase
    {
        private SerialPort _serialPort;

        private bool _isInputover;
        /// <summary>
        /// 是否输入完准考证
        /// </summary>
        public bool IsInputOver
        {
            get { return _isInputover; }
            set
            {
                _isInputover = value;
                RaisePropertyChanged("IsInputOver");
            }
        }

        private bool _isinputing = true;
        /// <summary>
        /// 是否在输入准考证
        /// </summary>
        public bool IsInputing
        {
            get { return _isinputing; }
            set
            {
                _isinputing = value;
                RaisePropertyChanged("IsInputing");
            }
        }

        private ExamineeInfoApi _examineeInfo;

        public ExamineeInfoApi ExamineeInfo
        {
            get { return _examineeInfo; }
            set { _examineeInfo = value; RaisePropertyChanged("ExamineeInfo"); }
        }

        private string _examNumber;
        /// <summary>
        /// 准考证号
        /// </summary>
        public string ExamNumber
        {
            get { return _examNumber; }
            set { _examNumber = value; RaisePropertyChanged("ExamNumber"); }
        }

        private string _serialPortState;
        /// <summary>
        /// 串口状态
        /// </summary>
        public string SerialPortState
        {
            get { return _serialPortState; }
            set { _serialPortState = value; RaisePropertyChanged("SerialPortState"); }
        }

        private ImageSource _imageSource;

        public ImageSource ImageSource
        {
            get { return _imageSource; }
            set { _imageSource = value; RaisePropertyChanged("ImageSource"); }
        }

        #region 命令
        public RelayCommand PracticeCommand { get; private set; }
        public RelayCommand BeginExamCommand { get; private set; }
        public RelayCommand ReturnCommand { get; private set; }
        public RelayCommand LoginCommand { get; private set; }
        #endregion

        public ExamineeLoginViewModel()
        {
            BeginExamCommand = new RelayCommand(BeginExamExec);
            ReturnCommand = new RelayCommand(ReturnExec);
            PracticeCommand = new RelayCommand(PracticeExec,()=>false);
            LoginCommand = new RelayCommand(LoginExec);

            InitSerialPort();
            
            Register<string>(this, MessageToken.SendNumberText,   (s => 
            {
                ExamNumber = s;
            }));

            Register(this, MessageToken.BackLogin, i =>
            {
                ClearBack();
            });
        }
        private void ReturnExec()
        {
            ClearBack();
        }

        private async void LoginExec()
        {
            if (string.IsNullOrEmpty(ExamNumber))
            {
                Send<string>(ExamNumber, MessageToken.ExameeLoginMessage);
            }
            else
            {
                dynamic result = await Login();
                var message = result.message;
                if (!result.issuccess)
                {
                    Send<string>(message, MessageToken.ShowLoginMessage);
                }
            }
        }

        private void InitSerialPort()
        {
            try
            {
                var config = ConfigTool.GetConfig().SingleOrDefault(i => i.name == "ComName");
                if (config == null)
                {
                    SerialPortState="初始化串口失败，检查config.txt ComName节点配置";
                    return;
                }
                _serialPort = new SerialPort();
                _serialPort.PortName = config.value;
                _serialPort.BaudRate = 19200;
                _serialPort.DataBits = 8;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                _serialPort.Open();
                SerialPortState = "串口已连接";
            }
            catch (Exception)
            {
                SerialPortState = "初始化串口失败，请检查串口配置";
            }
        }

        private void BeginExamExec()
        {
            var exammsg = new ExamMessage()
            {
                ExamineeInfo = ExamineeInfo,
                SerialPort = _serialPort
            };
            Send<ExamMessage>(exammsg, MessageToken.ShowExamingWindow);

        }

        private void PracticeExec()
        {
            Send<ExamineeInfoApi>(null,MessageToken.ShowExamingWindow);
        }

        private void ClearBack()
        {
            ExamNumber = String.Empty;
            ExamineeInfo = null;
            IsInputing = true;
            IsInputOver = false;
            Send(MessageToken.ClearNumberText);
        }
        

        public async Task<object> Login()
        {
            string message = String.Empty;
            bool issuccess = false;
            string getexamineeUrl = $"oplogin?nr={ExamNumber}&km=k4";
            Send<string>("获取考生信息......", MessageToken.ShowProgressMessage);
            await Task.Delay(500);
            ExamineeInfoApi result = null;
            try
            {
                result = await HttpTool.GetAsync<ExamineeInfoApi>(getexamineeUrl);
            }
            catch (Exception ex)
            {
                LogTool.UpServerLog(ex.StackTrace, EventType.Error);
            }

            Send<string>("获取考生信息......", MessageToken.CloseProgressMessage);
            await Task.Delay(500);
            if (result == null)
            {
                message = "获取失败，请尝试重新获取";
            }
            else if (result.status == 0)
            {
                if (result.wtadded == "低压电工作业" || result.wtadded == "高压电工作业")
                {
                    if (result.code.ToLower() == "k41")
                        issuccess = true;
                    else
                        message = "该考生不需要考核心肺复苏";
                }
                else if (result.wtadded == "熔化焊接与热切割作业")
                {
                    if (result.code.ToLower() == "k42")
                        issuccess = true;
                    else
                        message = "该考生不需要考核心肺复苏";
                }
                if (issuccess)
                {
                    ExamineeInfo = result;
                    if (!string.IsNullOrEmpty(result.photo))
                    {
                        ExamineeInfo.photoByte = Convert.FromBase64String(result.photo);
                        ImageSourceConverter converter = new ImageSourceConverter();
                        ImageSource = (ImageSource)converter.ConvertFrom(ExamineeInfo.photoByte);
                    }
                    else
                    {
                        ImageSource = new BitmapImage(new Uri(@"..\Image\nophoto.jpg", UriKind.Relative));
                    }

                    IsInputOver = true;
                    IsInputing = false;
                }
            }
            return new { message, issuccess };
        }
    }
}
